//============================================================================
// Name        : add_server.c
// Author      : Jessica Brazelton
// Course	   : CS 6210 Advanced Operating Systems
// Description :
//============================================================================

//================== HEADER FILES ==================
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <xmlrpc-c/base.h>
#include <xmlrpc-c/server.h>
#include <xmlrpc-c/server_abyss.h>


#define RANDPATH "/dev/random"

/*
 * This method will randomly return a value of heads or tails,
 * where 0 is heads and 1 is tails.
 */
static xmlrpc_value*
flipCoin(xmlrpc_env*   const envP,
			xmlrpc_value* const paramArrayP,
			void* const serverInfo,
			void* const channelInfo) {

	int fp, ret;
	unsigned int rand;

    if (envP->fault_occurred)
        return NULL;

	/* Return our result. */
    fp = open(RANDPATH, O_RDONLY);
    ret = read(fp, &rand, sizeof(rand));
    return xmlrpc_build_value(envP, "i", (rand % 2));
} // end flip coin

int main(int const argc, const char** const argv) {
    struct xmlrpc_method_info3 const methodInfo = {
        /* .methodName     = */ "flipCoin",
        /* .methodFunction = */ &flipCoin,
    };
    xmlrpc_server_abyss_parms serverparm;
    xmlrpc_registry * registryP;
    xmlrpc_env env;

    if (argc-1 != 1) {
        fprintf(stderr, "You must specify 1 argument:  The TCP port "
                "number on which the server will accept connections "
                "for RPCs (8080 is a common choice).  "
                "You specified %d arguments.\n",  argc-1);
        exit(1);
    }

    xmlrpc_env_init(&env);
    registryP = xmlrpc_registry_new(&env);
    xmlrpc_registry_add_method3(&env, registryP, &methodInfo);

    serverparm.config_file_name = NULL;
    serverparm.registryP        = registryP;
    serverparm.port_number      = atoi(argv[1]);
    serverparm.log_file_name    = "/tmp/xmlrpc_log";

    printf("Running XML-RPC server %s...\n", argv[1]);

    xmlrpc_server_abyss(&env, &serverparm, XMLRPC_APSIZE(log_file_name));

    /* xmlrpc_server_abyss() never returns */

    return 0;
}

